var twitter;

function Twitter() {
  this.searchUrl = createUrl('search');
  this.trendsCurrentUrl = createUrl('trends/current');
  this.trendsDailyUrl = createUrl('trends/daily');
  this.trendsWeeklyUrl = createUrl('trends/weekly');
}

function createUrl(method) {
  return 'http://search.twitter.com/' + method + '.json?callback=?';
}

function trends(type) {
  with(this) {
    var url = eval('twitter.trends' + type + 'Url');
    $.getJSON(url.toString(), function(data) {
      $.each(data.trends, function(i, date) {
        $.each(date, function(i, trend) { 
          $('ul#trends').append('<li><a href="' + trend.name + '" class="trend">' + trend.name + '</a></li>');
        });
      });
    });
  }
}

function trendsCurrent() { trends('Current'); }
function trendsDaily() { trends('Daily'); }
function trendsWeekly() { trends('Weekly'); }

function search(query) {
  with(this) {
    var options = '&rpp=100&q=' + encodeURIComponent(query);
    $.getJSON(this.searchUrl + options, function(data) {
      $.each(data.results, function(i, result) {
        result.text = result.text.replace(/https?:\/\/([-\w\.]+)+(:\d+)?(\/([\w/_\.]*(\?\S+)?)?)?/g, '<a href="$&">$&</a>');
        $('ul#results').append('<li><img src="' + result.profile_image_url + '" style="height:48px;width:48px" /> <a href="http://twitter.com/' + result.from_user + '" target="_blank">' + result.from_user + '</a> ' + result.text + '</li>');
      });
      ImageServices.loadThumbnails();
    });
  }
}

Twitter.prototype.createUrl = createUrl;
Twitter.prototype.search = search;
Twitter.prototype.trends = trends;
Twitter.prototype.trendsCurrent = trendsCurrent;
Twitter.prototype.trendsDaily = trendsDaily;
Twitter.prototype.trendsWeekly = trendsWeekly;

$(document).ready(function() {
  twitter = new Twitter();
  twitter.trendsDaily();
  
  $('a.trend').live('click', function(event) {
    event.preventDefault();
    $('ul#results').empty();
    twitter.search(this.innerHTML);
  });
});